<?php 
namespace app\index\model;
use think\Model;
use think\Session;
use think\Db;
use think\Request;  
use weibosdk\SaeTClientV2;  //微博
use weibosdk\SaeTOAuthV2;   //微博
use ucpaas\Ucpaas;          //手机号接口
use weixinsdk\Weixin;       //微信第三方
use qqsdk\Qqsdk;           //QQ登陆
header("Content-type: text/html; charset=utf-8");

class Login_model extends Model
{

    //登陆
	public function login($params)
	{
		$where = array (															
            'username'=>$params['username'],
        );
        $sql = Db::table('user')->where($where)->find();
        if($sql) {	
		}else{
			echo "<script> alert('用户名输入错误');location.href='login';</script>";die;
		}

     	$num=$sql['count'];
        //锁定
        if(time()-$sql['error_time']>1*3600)					//锁定1小时
        {  
            $num = 3;											//一小时后恢复默认登陆次数,3次
            $count=array(
            	'count'=>$num
            );
            Db::table('user')->where($where)->setField($count);
        }

        //验证密码是否错误
        if($num==0)
        {
          echo "<script> alert('密码输入次数过多,已锁定');location.href='login';</script>";die;
        }
        //md5验证码密码
        $params['password'] = md5($params['password']);

        //验证密码
     	if($params['password']!=$sql['password'])
        {
        	if($num == 0){
        	}else{
        		$num=($num-1);
        	}
            $time=time();
	        $linshi['count'] = $num;
	        $linshi['error_time'] = $time;
			$list = Db::table("user")->where('user_id',$sql['user_id'])->setField($linshi);
			if ($list) {
				echo "<script> alert('密码输入错误');location.href='login';</script>";die;
			}
        }

        //验证码
        if(request()->isPost()){
            if(!captcha_check($params['verifyCode'])) {
                // 校验失败
                echo "<script> alert('验证码输入错误');location.href='login';</script>";die;
            }
        }

        //成功
        $num=3;
		$linshi['count'] = $num;
		$list = Db::table('user')->where('user_id',$sql['user_id'])->setField($linshi); 

        $model = Db::table('address')->where('username',$sql['username'])->select();
        if ($model) {
            Session::set('ip',$model[0]['ip']);  
            Session::set('datatime',$model[0]['datatime']);
            Session::set('country',$model[0]['country']);
            Session::set('province',$model[0]['province']);
            Session::set('city',$model[0]['city']);
        }else{

            //获取IP地址
            $sql             = $sql['username'];      
            $res             = $this->close_ip($sql); 
        }
    
		Session::set('username',$sql['username']);   
     	// Session::set('admin',$sql['admin']);      // 暂停使用
		return $list;
	}


    //注册
    public function registered($params)
    {
        if (empty($params['username']))
        {
            echo "<script> alert('请输入用户名');history.go(-1);</script>";die;
        }
        if (empty($params['password']))
        {
            echo "<script> alert('请输入密码');history.go(-1);</script>";die;
        }
        if (empty($params['usernmae_email']))
        {
            echo "<script> alert('请输入邮箱');history.go(-1);</script>";die;
        }

        //验证用户名
        $where = array (                                                            
            'username'=>$params['username'],
        );
        $wherer = array (                                                            
            'usernmae_email'=>$params['usernmae_email'],
        );
        $sql = Db::table('user')->where($where)->find();
        if($sql) {  
            echo "<script> alert('用户名已存在');history.go(-1);</script>";die;
        }

        //验证邮箱
        $wherer = array (                                                            
            'usernmae_email'=>$params['usernmae_email'],
        );
        $sqll = Db::table('user')->where($wherer)->find();
        if($sqll) {  
            // 校验失败
            echo "<script> alert('邮箱已存在');history.go(-1);</script>";die;
        }

        //验证码
        if(request()->isPost()){
            if(!captcha_check($params['verifyCode'])) {
                // 校验失败
                echo "<script> alert('验证码输入错误');history.go(-1);</script>";die;
            }
        }
        $url = 'http://img2.imgtn.bdimg.com/it/u=788553782,2956532724&fm=27&gp=0.jpg';
        $data['username']       = $params['username'];        //用户名   
        $data['password']       = md5($params['password']);   //md5加密
        $data['data_time']      = date('Y-m-d H:i:s',time()); //注册时间
        $data['username_img']   = $url;                       //头像
        $data['usernmae_email'] = $params['usernmae_email'];  //邮箱
        $data['username_Identification'] = '网站注册';        //用户注册标识
        $registered = Db::table('user')->insert($data);
        return $registered;
    }

    //手机验证码
    public function yzm($params)
    {
        //短信接口
        $mobile = $params;               //用户手机
        $param = rand(10000,99999);      //生成随机数验证码
        session::set('yzm',$param);      //验证码存入session用于最后的验证

        $options['accountsid']= YZM_accountsid;    //开发者控制台首页上的Account Sid
        $options['token']= YZM_token;              //开发者控制台首页上的Auth Token

        $ucpaas = new Ucpaas($options);    
        $appid = YZM_appid;                                             //应用的ID，可在开发者控制台内的短信产品下查看
        $templateid = YZM_templateid;                                   //可在后台短信产品→选择接入的应用→短信模板-模板ID，查看该模板ID
        $result = $ucpaas->SendSms($appid,$templateid,$param,$mobile);  //短信类的方法
        
        $code = json_decode($result)->count;                              //获取状态码
        print_r($code);die;
    }

    //微博 code_url 地址
    public function code_url()
    {
        $obj = new SaeTOAuthV2(WB_AKEY,WB_SKEY);
        $code_url = $obj->getAuthorizeURL(WB_CALLBACK_URL);
        return $code_url;
    }

    //微信 weixin_url 地址
    public function weixin_url()
    {
        $WX_APPID = WX_APPID;
        $redirectUrl = urlencode("http://www.close.com/index/login/weixin.html");
        $weixin_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $WX_APPID . '&redirect_uri=' . $redirectUrl . '&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect';
        return $weixin_url;
        
    }

    //QQ qq_url 地址
    public function qq_url()
    {
        $app_id = QQ_APPID;
        $redirect = QQ_APPURL;
        $qq_url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=' . $app_id . '&redirect_uri=' . $redirect;  
        return $qq_url;
        
    }

    //微博登陆
    public function weibo()
    {
        //获取微博code
        $obj = new SaeTOAuthV2(WB_AKEY,WB_SKEY);
        $keys = array();
        $params = Request::instance()->param();
        if(array_key_exists('code', $params)){
    
        }else{
          echo "<script> alert('取消授权');location.href='login';</script>";die;
        }
        $keys['code'] = $params['code'];
        $keys['redirect_uri'] = WB_CALLBACK_URL;
        $token = $obj -> getAccessToken('code',$keys);
        
        //获取用户信息
        $open_data = new SaeTClientV2(WB_AKEY,WB_SKEY,$token['access_token']);  
        $ms = $open_data->home_timeline();                                      //微博内容
        $uid_get = $open_data->get_uid();                                       //用户id
        $user_message = $open_data->show_user_by_id($uid_get['uid']);           //获取用户信息

        //组装数据
        $params['username'] = 'WB'.$user_message['screen_name'];           //获取用户名
        $params['password'] = date('Y-m-d H:i:s',time());             //密码
        $parame['username_img'] = $user_message['profile_image_url']; //获取用户头像
        
        // 入库数据
        $uid_get = $uid_get['uid'];
        $sql = Db::table('user')->where('username_uid_openid',$uid_get)->find();
        if($sql) {  
            $data['username']     = $params['username'];        //用户名
            $data['username_img'] = $parame['username_img'];    //头像
            $list = Db::table("user")->where('username_uid_openid',$uid_get)->setField($data);
        }else{
            $data['username']  = $params['username'];        //用户名
            $data['password']  = md5($params['password']);   //md5加密密码
            $data['data_time'] = date('Y-m-d H:i:s',time()); //注册时间
            $data['username_img'] = $parame['username_img']; //头像
            $data['username_uid_openid'] = $uid_get;         //微博用户唯一标识
            $data['username_Identification'] = '新浪微博';   //用户注册标识
            $registered = Db::table('user')->insert($data);
        }

        //用户的登陆时间 地址  IP 等信息
        $model = Db::table('address')->where('username',$params['username'])->select();
        if ($model) {
            Session::set('ip',$model[0]['ip']);  
            Session::set('datatime',$model[0]['datatime']);
            Session::set('country',$model[0]['country']);
            Session::set('province',$model[0]['province']);
            Session::set('city',$model[0]['city']);
        }else{
            //获取IP地址
            $sql             = $sql['username'];      //下边 close_ip 分装获取ip的类了,
            $res             = $this->close_ip($sql); 
        }
        Session::set('username',$params['username']); 
        return $model;
    }


    //微信登陆
    public function weixin($params)
    {
        $code = $params["code"]; 

        $url  = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . WX_APPID . '&secret=' . WX_appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $res  = $this->https_request($url);     //调用方法
        $res  = (json_decode($res, true));      //json转数组,最终得到的用户信息
        $access_token = $res['access_token'];   //ac取出cess_token
        $openid       = $res['openid'];         //openid,用户唯一标识
        
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid;
        $res = $this->https_request($url);       //调用方法
        $res = json_decode($res, true);          //json转数组,最终得到的用户信息

        $params['username']       = 'WX'.$res['nickname'];      //微信用户名称
        $params['password']       = date('Y-m-d H:i:s',time()); //密码
        $params['username_img']   = $res['headimgurl'];         //微信用户头像
        
        $uid_get = $res['openid'];
        //接uid_get参数,查询是否有唯一的openid, 
        $sql = Db::table('user')->where('username_uid_openid',$uid_get)->find();
        if ($sql) {
            $data['username']        = $params['username'];         //微信用户名称
            $data['username_img']    = $params['username_img'];     //微信用户头像
            $list = Db::table("user")->where('username_uid_openid',$uid_get)->setField($data);
        }else{
            echo "string";
            $data['username']                 = $params['username'];        //微信用户名称
            $data['password']                 = md5($params['password']);   //md5加密密码
            $data['data_time']                = date('Y-m-d H:i:s',time()); //注册时间
            $data['username_img']             = $params['username_img'];    //微信用户头像
            $data['username_uid_openid']      = $uid_get;                   //openid,用户唯一标识
            $data['username_Identification']  = '微信注册';                 //用户注册标识
            $registered = Db::table('user')->insert($data);
        }

        //用户的登陆时间 地址  IP 等信息
        $model = Db::table('address')->where('username',$params['username'])->select();
        if ($model) {
            Session::set('ip',$model[0]['ip']);  
            Session::set('datatime',$model[0]['datatime']);
            Session::set('country',$model[0]['country']);
            Session::set('province',$model[0]['province']);
            Session::set('city',$model[0]['city']);
        }else{

            //获取IP地址
            $sql             = $sql['username'];      //下边 close_ip 分装获取ip的类了,
            $res             = $this->close_ip($sql); 
        }
        Session::set('username',$params['username']); 
        return $model;
    }

    //QQ登陆
    public function qqlogin($params)
    {
        $code = $params["code"]; 
        $qq_sdk = new Qqsdk();   
        $token = $qq_sdk->get_access_token($code);
        $open_id = $qq_sdk->get_open_id($token['access_token']); 
        $res = $qq_sdk->get_user_info($token,$open_id);
        //组装数据
        $params['username'] = 'QQ'.$res['nickname'];             //获取用户名
        $params['password'] = date('Y-m-d H:i:s',time());   //密码
        $parame['username_img'] = $res['figureurl_2'];      //获取用户头像
        
        // 入库数据
        $uid_get = $open_id['openid'];
        $sql = Db::table('user')->where('username_uid_openid',$uid_get)->find();
        if($sql) {  
            $data['username']     = $params['username'];        //用户名
            $data['username_img'] = $parame['username_img'];    //头像
            $list = Db::table("user")->where('username_uid_openid',$uid_get)->setField($data);
        }else{
            $data['username']  = $params['username'];        //用户名
            $data['password']  = md5($params['password']);   //md5加密密码
            $data['data_time'] = date('Y-m-d H:i:s',time()); //注册时间
            $data['username_img'] = $parame['username_img']; //头像
            $data['username_uid_openid'] = $uid_get;         //微博用户唯一标识
            $data['username_Identification'] = 'QQ登陆';     //用户注册标识
            $registered = Db::table('user')->insert($data);
        }
         //用户的登陆时间 地址  IP 等信息
        $model = Db::table('address')->where('username',$params['username'])->select();
        if ($model) {
            Session::set('ip',$model[0]['ip']);  
            Session::set('datatime',$model[0]['datatime']);
            Session::set('country',$model[0]['country']);
            Session::set('province',$model[0]['province']);
            Session::set('city',$model[0]['city']);
        }else{
             //获取IP地址
            $sql             = $sql['username'];      //下边 close_ip 分装获取ip的类了,
            $res             = $this->close_ip($sql); 
        }
        Session::set('username',$params['username']); 
        return $model;
    }


    //微信生成token
    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }



    //获取ip 位置信息
    function close_ip($sql)
    {
        $ip                = $_SERVER['REMOTE_ADDR'];
        $json              = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip);
        $json              = json_decode($json, true);
        $data['ip']        = $ip;
        $data['username']  = $sql['username'];
        $data['datatime']  = date('Y-m-d H:i:s',time());
        $data['country']   = $json["country"];
        $data['province']  = $json["province"];
        $data['city']      = $json["city"];
        $data['district']  = $json["district"];
        $data['isp']       = $json["isp"];
        $arr = Db::table('address')->insert($data);
    }
}